package at.bartinger.snake;

import android.content.Context;


public class Game{

	public double RADTODEG = 180/Math.PI;


	public Snake snake;
	public double dirX=0.5d;
	public double dirY=0.5d;

	private boolean stop = false;
	

	private int delay;

	public Bonus bonus;
	private int bonusTime;
	private int countToBonus;
	public boolean isBonusadded = false;
	public boolean isBonusselected = false;
	public boolean hasScoreChanged = false;
	public boolean isOver = false;

	public int score = 0;

	public Game(Context context, Snake snake,int delay, Bonus bonus) {
		this.snake = snake;
		this.bonus = bonus;
		this.delay = delay;
		bonusTime= 1500/delay;
		
	}


	public void update() {
		hasScoreChanged = false;
		if(dirX !=0 && dirY !=0 && !stop){
			snake.move(dirX,dirY);
			snake.wallHit();

			if(snake.selfHit()){
				GameOver();
			}

			if(bonusTime == countToBonus){
				isBonusadded = true;
				bonus.addBonusElement();
				countToBonus=0;
			}


			if(isBonusadded){
				if(snake.headhitBonus(bonus.bonus)){
					if(snake.getSnake().size()==30){
						//next level
					}
					hasScoreChanged = true;
					isBonusadded = false;
					snake.addNewElement();
					score+=bonus.value+snake.getSnake().size();
					if(delay != 0){
						delay--;
					}
				}
			}else countToBonus++;
		}

		try {
			Thread.sleep(delay);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}



	}
	

	public void setDirections(float x, float y){

		double difX  = (x-snake.getSnake().get(0).x);
		double difY  = (y-snake.getSnake().get(0).y);
		double difLength = Math.sqrt(difX*difX + difY*difY);
		double dirnewX =(difX / difLength);
		double dirnewY =(difY / difLength);
		double alpha = getAlpha(dirnewX,dirnewY,dirX,dirY);
		if(alpha < 140){
			dirX = dirnewX;
			dirY = dirnewY;
		}
	}


	public double getAlpha(double x1, double y1, double x2, double y2){
		return RADTODEG*Math.acos(((x1*x2)+(y1*y2))/(Math.sqrt((x1*x1)+(y1*y1))*Math.sqrt((x2*x2)+(y2*y2))));
	}


	private void GameOver(){
		stop=true;
		isOver=true;
		FingerSnake.score = score;
	}

}
